package com.example.demo.controller;

import com.example.demo.domain.result.StudentInfo;
import com.example.demo.exception.NotSupportException;
import com.example.demo.exception.PasswordErrorException;
import com.example.demo.result.ApiResult;
import com.example.demo.result.ResultCode;
import com.example.demo.utils.HbutEtcLoginUtil;
import com.example.demo.utils.LogUtil;
import com.example.demo.utils.ParseUtil;
import com.google.gson.Gson;
import javax.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.Map;

/**
 * @author lizijian
 */
@RestController
@RequestMapping("/School")
@Slf4j
@Validated
public class AuthenticationController {


  @Autowired
  private RestTemplate restTemplate;

  @Value("${api1}")
  private String api1;

  @Value("${api2}")
  private String api2;


  @GetMapping("/authentication")
  public ApiResult<StudentInfo> authentication(
      @NotNull(message = "campusId参数不能为空") Integer campusId,
      @NotBlank(message = "缺少username参数") String username,
      @NotBlank(message = "缺少password参数") String password)
      throws IOException, PasswordErrorException, NotSupportException {
    StudentInfo studentInfo = null;
    if (campusId == 1) {
      studentInfo = ParseUtil.getStuInfo(username, password);
    } else if (campusId == 2) {
      studentInfo = HbutEtcLoginUtil.getStudentInfo(username, password);
    }
    String taskId = LogUtil.getTaskId();
    MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<>();
    requestMap.add("code", taskId);
    requestMap.add("schoolId", username);
    HttpEntity requestEntity = new HttpEntity(requestMap, null);
    ResponseEntity<String> response = restTemplate.postForEntity(api2, requestEntity, String.class);
    Map<String, String> resultMap = new Gson().fromJson(response.getBody(), Map.class);
    String resultCode = resultMap.get("code");
    log.info(LogUtil.getMessage("resultCode:" + resultCode));
    if (!"00000".equals(resultCode)) {
      return ApiResult.fail(ResultCode.SYSTEM_ERROR, "send code failed", "发送code失败", null);
    }
    studentInfo.setCode(taskId);
    return ApiResult.success(studentInfo);
  }
}
